package com.youngball.web.config;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;

/**
 * Created by asus on 2016/6/17.
 */
@SuppressWarnings({"rawtypes", "unchecked"})
@Intercepts(@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}))
public class BaseInfoInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
               Object object= invocation.getArgs()[1];
     if (object!=null) {
         buildProperty(object,"id", UUID.randomUUID().toString());
         buildProperty(object,"createAt",new Date());
        }
        return invocation.proceed();
    }

    /*为某一属性的赋值*/
    public void buildProperty(Object object,String key,Object value){
        try {
             Class clazz=object.getClass();
            Field   field = clazz.getDeclaredField(key);
            field.setAccessible(true);
            String id = (String) field.get(object);
            if (id == null) {
                field.set(object,value);
            }
        } catch (NoSuchFieldException e) {
    /*        e.printStackTrace();*/
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        } else {
            return target;
        }
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
